package auth

import (
	"log"

	"github.com/casbin/casbin/v2"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	"gorm.io/gorm"
)

// CasbinEnforcer Casbin执行器
var CasbinEnforcer *casbin.Enforcer

// InitCasbin 初始化Casbin
func InitCasbin(db *gorm.DB) {
	adapter, err := gormadapter.NewAdapterByDB(db)
	if err != nil {
		log.Fatalf("Failed to initialize casbin adapter: %v", err)
	}

	enforcer, err := casbin.NewEnforcer("configs/rbac_model.conf", adapter)
	if err != nil {
		log.Fatalf("Failed to create casbin enforcer: %v", err)
	}

	// 加载策略
	err = enforcer.LoadPolicy()
	if err != nil {
		log.Fatalf("Failed to load casbin policy: %v", err)
	}

	// 设置默认策略
	// 管理员可以执行所有操作
	_, err = enforcer.AddPolicy("admin", "*", "*")
	if err != nil {
		log.Printf("Failed to add admin policy: %v", err)
	}

	// 普通用户只能操作自己的资源
	_, err = enforcer.AddPolicy("user", "/api/todos", "GET")
	if err != nil {
		log.Printf("Failed to add user policy: %v", err)
	}
	_, err = enforcer.AddPolicy("user", "/api/todos", "POST")
	if err != nil {
		log.Printf("Failed to add user policy: %v", err)
	}
	_, err = enforcer.AddPolicy("user", "/api/todos/:id", "GET")
	if err != nil {
		log.Printf("Failed to add user policy: %v", err)
	}
	_, err = enforcer.AddPolicy("user", "/api/todos/:id", "PUT")
	if err != nil {
		log.Printf("Failed to add user policy: %v", err)
	}
	_, err = enforcer.AddPolicy("user", "/api/todos/:id", "DELETE")
	if err != nil {
		log.Printf("Failed to add user policy: %v", err)
	}

	CasbinEnforcer = enforcer
	log.Println("Casbin initialized successfully")
}